<?php

class PapiWS_Model_TextBoxRenderer {
	
	// Imagemagick image
	public $canvas = null; 


	public function __construct( $image )
	{
		$this->canvas = $image;
	}

	public function render( $textbox ) {


		$affine = new PapiWS_Model_AffineTransformation();
		$affine->rotate( $textbox->angle );
		$affine->translate(
			$this->mmToPx($textbox->x), 
			$this->mmToPx($textbox->y)
		);

		$draw = new ImagickDraw();
		$draw->affine( $affine->getCurrentMatrix() );


		// setup vars
		//$lineHeight = $textbox->lineHeight;
		$lineHeight = $this->ptToPx( round( $textbox->fontSize * 1.1 ) );
		$rgbColor = sprintf( "#%06x", $textbox->fontColor );
		$draw->setFillColor( $rgbColor );
		$draw->setFillAlpha( $textbox->alpha );
		//$draw->setFont('/usr/src/redhat/BUILD/msttcorefonts/fonts/comic.ttf');
		$draw->setFont('/home/miquel/Work/Ext/svn/PersonalizationEditor/trunk/assets/fonts/copacetix.ttf');
		$draw->setFontSize( $this->ptToPx( $textbox->fontSize ) );

		// draw text
		$lines = explode( "\r", $textbox->text );
		$x = $this->mmToPx( $textbox->x );
		$y = $this->mmToPx( $textbox->y );
		$x = 0; $y = $lineHeight;
		foreach( $lines as $line ) {
			$draw->annotation( $x, $y, $line );
			$y += $lineHeight;
		}

		if ( $textbox->hasDropShadow ) {
			// handle shadow.
			true;
		}

		$this->canvas->drawImage( $draw );

	}

	// TODO: Mover esto a otro lado.
    function mmToPx( $length )
    {
        // TODO get from conf. Take into account
        // the fact that output DPI != input DPI !!!!
        $dpi = 200;
        $lengthPx = $length * $dpi / 25.4;
        return (int) round( $lengthPx );
    }

	function ptToPx( $length )
    {
        // TODO get from conf. Take into account
        // the fact that output DPI != input DPI !!!!
        $dpi = 200;
        $lengthPx = $length * $dpi / 72;
        return (int) round( $lengthPx );
    }

}
